/*
 * 描述
 * Created by: litangyu
 * 包含类名列表
 * 版本信息，版本号 v1.0
 * 创建日期 16/9/7
 * 版权声明
*/
package com.foton.logistic.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.foton.logistic.R;
import com.foton.logistic.adapter.UploadImageAdapter;
import com.foton.logistic.base.BaseActivity;
import com.foton.logistic.base.BaseApplication;
import com.foton.logistic.listener.IOnDeleteListener;
import com.foton.logistic.listener.IOnDialogListener;
import com.foton.logistic.listener.IOnResultListener;
import com.foton.logistic.task.DispatchTask;
import com.foton.logistic.task.ShowDialogTask;
import com.foton.logistic.task.TaskConstant;
import com.foton.logistic.util.BaseConstant;
import com.foton.logistic.util.BroadcastUtil;
import com.foton.logistic.util.OptionUtil;
import com.foton.logistic.util.SharedUtil;
import com.foton.logistic.util.image.ImageChooseUtil;
import com.foton.logistic.util.net.HttpUtil;
import com.foton.logistic.util.tool.DataCleanManager;
import com.foton.logistic.util.tool.LogUtil;
import com.foton.logistic.util.tool.StringUtil;
import com.foton.logistic.view.MyGridView;
import com.foton.logistic.view.chooseimages.ImagesPreviewUtil;
import com.foton.logistic.view.dialog.DialogUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 描述
 * 上传图片
 * Created by: litangyu<br/>
 * Created on: 16/9/7 上午10:50
 */
@RuntimePermissions
public class UploadImageActivity extends BaseActivity {

    @InjectView(R.id.ft_ui_upload_abnormal_select_reason)
    public LinearLayout selectReasonLayout;

    @InjectView(R.id.ft_ui_upload_abnormal_images)
    public MyGridView uploadImages;
    @InjectView(R.id.ft_ui_upload_abnormal_tip)
    public TextView tipText;
    @InjectView(R.id.ft_ui_upload_lin)
    LinearLayout ftUiUploadLin;

    private UploadImageAdapter adapter;

    private String orderId;
    private int type;

    private int statusBarHeight;

    private int addImagePosition = -1;
    private ImageChooseUtil imageChooseUtil;
    private ArrayList<String> mSelPhotos;
    //获取地址
    private String address = "";
    private GeoCoder mSearch;
    public DialogUtil dialogUtil;
    public PopupWindow loadPopupWindow;//加载框
    private PopupWindow myPopuwindiw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setTaskTag(getClass().getSimpleName());
        setContentView(R.layout.ft_ui_upload_abnormal);
        ButterKnife.inject(this);
    }

    @Override
    protected void onDestroy() {
        mSearch.destroy();
        if (loadPopupWindow!=null) {
            loadPopupWindow.dismiss();
        }
        if (myPopuwindiw!=null) {
            myPopuwindiw.dismiss();
        }
        super.onDestroy();
    }

    @Override
    public void init() {
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);
        dialogUtil = new DialogUtil(this);

        getOrderId();

        setBackLayoutVisibility(View.VISIBLE);
        setTitleText(getString(R.string.upload_image));
        setTitleTextVisibility(View.VISIBLE);
        ftUiUploadLin.setVisibility(View.GONE);
        selectReasonLayout.setVisibility(View.GONE);
        tipText.setVisibility(View.VISIBLE);
        if (type == 0) {
            tipText.setText(getString(R.string.upload_tip1));
            setTitleText(getString(R.string.upload_title1));
        } else {
            tipText.setText(getString(R.string.upload_tip2));
            setTitleText(getString(R.string.upload_title2));
        }
        statusBarHeight = OptionUtil.getStatusBarHeight(this);
        imageChooseUtil = new ImageChooseUtil(this);

        mSelPhotos = new ArrayList<>();

        adapter = new UploadImageAdapter(this, mSelPhotos, BaseConstant.MAX_PHOTO, false);
        uploadImages.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            private ImagesPreviewUtil imagesPreviewUtil;

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == mSelPhotos.size()) {
                    addImagePosition = position;
                    UploadImageActivityPermissionsDispatcher.checkPhotoWithCheck(UploadImageActivity.this);
                    //imageChooseUtil.doTakePhotos();
                } else {
                    if (null == imagesPreviewUtil) {
                        imagesPreviewUtil = new ImagesPreviewUtil
                                (UploadImageActivity.this, mSelPhotos, titleText);
                        imagesPreviewUtil.setShowDelete(true);
                        imagesPreviewUtil.setStatusBarHeight(statusBarHeight);
                        myPopuwindiw =imagesPreviewUtil.showImagesPreview(position);
                        imagesPreviewUtil.setiOnDeleteListener(new IOnDeleteListener() {
                            @Override
                            public void onDelete(int position) {
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        myPopuwindiw =imagesPreviewUtil.showImagesPreview(position);
                    }
                }
            }
        });
        uploadImages.setAdapter(adapter);
        address = SharedUtil.getAddress(this);
        LogUtil.e("address= " + address);
        if (StringUtil.isEmpty(address)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadPopupWindow = dialogUtil.showLoadDialog(titleText, "获取当前地址");
                    LatLng ll = new LatLng(Double.parseDouble(SharedUtil.getLat(BaseApplication.self())), Double.parseDouble(SharedUtil.getLng(BaseApplication.self())));
                    ReverseGeoCodeOption options = new ReverseGeoCodeOption().location(ll);
                    // 发起反地理编码请求
                    mSearch.reverseGeoCode(options);
                }
            }, 500);

        } else {
            OptionUtil.addToast(BaseApplication.self(), "获取当前地址成功");
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        getOrderId();
    }

    /**
     * 获取订单编号
     */
    private void getOrderId() {
        if (null != getBundle()) {
            orderId = getBundle().getString(BaseConstant.INTENT_ID, "");
            type = getBundle().getInt(BaseConstant.INTENT_TYPE, 0);
        }
    }

    @OnClick(R.id.ft_ui_upload_abnormal_submit)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ft_ui_upload_abnormal_submit:
                request();
                break;
        }
    }

    @Override

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case ImageChooseUtil.PHOTO_WITH_CAMERA: // 照相机程序返回的
                        String imagePath = imageChooseUtil.getTakePhotoScaleUrl(address);
                        DataCleanManager.DeleteFile(new File(imageChooseUtil.getTakePhotosUrl()));
                        if (!StringUtil.isEmpty(imagePath) && addImagePosition != -1) {
                            mSelPhotos.add(imagePath);
                            adapter.notifyDataSetChanged();
                        } else {
                            OptionUtil.addToast(UploadImageActivity.this, getString(R.string
                                    .tip8));
                        }
                        break;
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void request() {
        String uploadImagePath = null;
        if (mSelPhotos.size() < 2) {
            OptionUtil.addToast(this, getString(R.string.limit_photo));
            return;
        } else {
            for (String imagePath : mSelPhotos) {
                if (StringUtil.isEmpty(uploadImagePath)) {
                    uploadImagePath = imagePath;
                } else {
                    uploadImagePath = uploadImagePath + "," + imagePath;
                }
            }
        }
        List<File> fileList = OptionUtil.getImageList(uploadImagePath);
        Map<String, Object> argMap = HttpUtil.getEncryMap(this);
        argMap.put("orderId", "" + orderId);
        if (type == 0) {
            argMap.put("type", "2");
        } else {
            argMap.put("type", "5");
        }
        argMap.put("lat", SharedUtil.getLat(this));
        argMap.put("lon", SharedUtil.getLng(this));
        argMap.put("address", SharedUtil.getAddress(this));

        ShowDialogTask task = new ShowDialogTask(this, taskTag, titleText, getString(R.string.task3), true,
                BaseConstant.UPLOAD_IMAGE, argMap, fileList, TaskConstant.UPLOADS);
        task.setiOnResultListener(new IOnResultListener() {
            @Override
            public void onOK(DispatchTask task) {
                OptionUtil.addToast(UploadImageActivity.this, getString(R.string
                        .upload_image_success));
                BroadcastUtil.sendOrderRefreshBroadcast(UploadImageActivity.this);
                finishSelf();
            }

            @Override
            public void onError(DispatchTask task) {

            }

            @Override
            public void onDone(DispatchTask task) {

            }
        });
        task.execute();
    }

    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }
            //获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            LogUtil.e("result.error= " + result.error);
            if (loadPopupWindow != null)
                loadPopupWindow.dismiss();
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
                dialogUtil.setOptionCount(1);
                dialogUtil.showTipDialog(titleText, "获取当前地址失败，请退出界面后重试");
                dialogUtil.setiOnDialogListener(new IOnDialogListener() {
                    @Override
                    public void onConfirm() {
                        finishSelf();
                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onOther() {

                    }
                });
            } else {
                //获取反向地理编码结果
                address = result.getAddress();
                OptionUtil.addToast(BaseApplication.self(), "获取当前地址成功");
            }

        }
    };

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void checkPhoto() {
        imageChooseUtil.doTakePhotos(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        UploadImageActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
}
